#include "usart.h"  
#include "user_type.h"
#include "funcs.h"
#include "stm32f10x.h" 

void NVIC_usart1_init()
{
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
}
void Port_usart1_init()
{
/*端口时钟启用*/
	GPIO_InitTypeDef  GPIO_InitStruct;
	RCC_APB2PeriphClockCmd(PORT_CLK_USART1,ENABLE);/*开启gpio引脚的时钟*/


   /*配置tx引脚*/
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP;//复用功能推挽输出
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_9;//tx 
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;//
	GPIO_Init(GPIOA,&GPIO_InitStruct);
 
 /*rx引脚*/
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IN_FLOATING;//引脚浮空
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_10;//rx 
	GPIO_Init(GPIOA,&GPIO_InitStruct); 

 
}



// void hal_usart_init(USART_TypeDef* USARTx)
// {
// 	USARTx->CR1
// } 
void uart_init(void)
{
	USART_InitTypeDef USART_InitStruct;
	Port_usart1_init();
	NVIC_usart1_init();//串口中断优先级配置
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//usart1时钟开启

	/*usart1具体配置*/
	USART_InitStruct.USART_BaudRate = 115200;//根据给定波特率自动计算
    USART_InitStruct.USART_WordLength = USART_WordLength_9b;//字长，选择1为9字节
	USART_InitStruct.USART_Parity = USART_Parity_Odd;//校验方式
	USART_InitStruct.USART_StopBits = USART_StopBits_1;//
	USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

	USART_Init(USART1, &USART_InitStruct);//串口初始化配置

//中断启用 
	// USART_ITConfig(USART1, USART_IT_TXE, ENABLE);//发送缓冲区空,st.txe=1
	// USART_ITConfig(USART1, USART_IT_IDLE, ENABLE);//总线空闲中断,sr.idle 
	// USART_ITConfig(USART1, USART_IT_TC, ENABLE);//发送完成,sr.tc=1

	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//接收缓冲区非空，sr.ore/rxne=1 

	USART_Cmd(USART1, ENABLE);//使能串口
} 
#define timeDelay  500
void Usart_Sendstring( USART_TypeDef * pUSARTx, char* str,uint8_t len)
{  
	static uint8_t flg = 0u;
	int i = 0;
	uint8_t ch ; 
	flg++;
	if(flg>1)
	{
		flg = 0;
		return; 
	}
	for(i=0;i<len;i++)
	{
	ch = (uint8_t)str[i];
	USART_SendData(pUSARTx,ch); //数据不能发太快，否则乱码
	while (USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET);
	} 
	 flg = 0u;  
}  
void Usart_SendCharArray( USART_TypeDef * pUSARTx, char* str,uint8_t len)
{   	
	static uint8_t flg = 0u;
	int i = 0;  
	flg++;
	if(flg>1)
	{
		flg = 0;
		return;
	}
	for(i=0;i<len;i++)
	{ 
	USART_SendData(pUSARTx,str[i]); //数据不能发太快，否则乱码
	while (USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET);
	} 
	flg = 0u; 
} 

